Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change compression prior to encryption for best results #351

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

ragmehos
Copy link
Contributor

@ragmehos ragmehos commented Nov 12, 2024

Config string length : 1297 characters

Compression after encryption : 1789 characters.

Compression before encryption : 833 characters.

This is much efficient in general cause base text has better compression than encrypted text. As you can see, compression after encryption leads to more characters than the original config string length itself without compression.

This change will break existing installation - this PR is to get comments first before figuring out backwards compatibility required to make it work with existing configs too if needed.

Another improvement that can be achieved is to also convert fields like tamil_hdrip etc to more efficient strings like "thd" etc. That should keep the URL length very short.

Summary by CodeRabbit

  • New Features

    • Enhanced encryption process by compressing text before encryption and decompressing after decryption, improving data handling.
  • Bug Fixes

    • Improved extraction of the initialization vector (IV) during the decryption process.

Copy link
Contributor

coderabbitai bot commented Nov 12, 2024

Walkthrough

The changes in this pull request modify the encrypt_text and decrypt_text functions in utils/crypto.py. The encrypt_text function now compresses the input text using zlib.compress prior to encryption, and the initialization vector (IV) is directly encoded with the encrypted data. The decrypt_text function extracts the IV from the decoded data and includes a decompression step using zlib.decompress after decryption. Other related functions remain unchanged.

Changes

File Change Summary
utils/crypto.py Modified encrypt_text to compress input text before encryption and adjusted IV handling. Updated decrypt_text to extract IV from decoded data and added decompression after decryption. Other functions remain unchanged.

Poem

🐇 In the burrow, secrets weave,
Texts now dance, as we believe.
Compressed whispers, encrypted tight,
Decrypted dreams take flight at night.
Zlib magic in the air,
Hopping joy, without a care! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
utils/crypto.py (1)

Line range hint 1-38: Consider alternative approaches and migration strategy

While compressing before encryption is more efficient, the current implementation introduces several concerns:

  1. Breaking Changes:

    • Existing encrypted configurations will fail to decrypt
    • Need for a migration strategy or backward compatibility
  2. Security Considerations:

    • Compression before encryption needs careful analysis of potential oracle attacks
    • Consider if the compression gain justifies the security complexity
  3. Alternative Approaches:

    • Instead of modifying the encryption process, consider:
      • Using shorter field names in the JSON structure
      • Implementing a more efficient encoding scheme
      • Using a binary serialization format like Protocol Buffers

Recommendations:

  1. Add a version identifier to support both old and new formats
  2. Document the breaking changes and provide migration scripts
  3. Add comprehensive security tests for compression-related attacks
  4. Consider implementing the suggested alternative approaches first
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2b822b0 and 7d43872.

📒 Files selected for processing (1)
  • utils/crypto.py (1 hunks)
🔇 Additional comments (1)
utils/crypto.py (1)

22-26: ⚠️ Potential issue

Security: Evaluate compression oracle attacks and use standard padding

The implementation has several security considerations:

  1. Compressing data before encryption could be vulnerable to compression oracle attacks (like CRIME/BREACH) if the data contains both secrets and attacker-controlled input.
  2. Using custom null byte padding instead of standard PKCS7 padding (from Crypto.Util.Padding) is risky.

Let's verify if there's any attacker-controlled input being encrypted:

Suggested fixes:

- encoded_text = zlib.compress(text.encode("utf-8"))
- encrypted_data = cipher.encrypt(
-     encoded_text + b"\0" * (16 - len(encoded_text) % 16)
- )
+ encoded_text = zlib.compress(text.encode("utf-8"))
+ padded_data = pad(encoded_text, AES.block_size)
+ encrypted_data = cipher.encrypt(padded_data)

Comment on lines 37 to +38
decrypted_data = decrypted_data.rstrip(b"\0")
return decrypted_data.decode("utf-8")
return zlib.decompress(decrypted_data).decode("utf-8")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling and backward compatibility

The decompression step lacks error handling and breaks backward compatibility with existing encrypted data.

  1. Add error handling for decompression:
 decrypted_data = decrypted_data.rstrip(b"\0")
- return zlib.decompress(decrypted_data).decode("utf-8")
+ try:
+     return zlib.decompress(decrypted_data).decode("utf-8")
+ except zlib.error:
+     # Attempt backward compatibility with uncompressed data
+     try:
+         return decrypted_data.decode("utf-8")
+     except UnicodeDecodeError:
+         raise ValueError("Failed to decrypt: invalid data format")
  1. Consider adding a version byte to the encrypted data to properly handle both compressed and uncompressed formats:
# In encrypt_text:
version = b'\x01'  # Version 1: compressed
encrypted_str = urlsafe_b64encode(version + iv + encrypted_data).decode("utf-8")

# In decrypt_text:
version = decoded_data[0:1]
iv = decoded_data[1:17]
if version == b'\x01':
    # Handle compressed data
else:
    # Handle uncompressed data

Comment on lines +32 to +36
iv = decoded_data[:16]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
cipher = AES.new(secret_key.ljust(32)[:32], AES.MODE_CBC, iv)
decrypted_data = cipher.decrypt(encrypted_data[16:])
decrypted_data = cipher.decrypt(decoded_data[16:])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add input validation for IV and ciphertext

The function lacks crucial input validation which could lead to security issues:

  1. No validation of IV length (should be 16 bytes)
  2. No validation of decoded data length (should be at least IV length + block size)

Apply this fix:

 decoded_data = urlsafe_b64decode(secret_str)
+ if len(decoded_data) < 32:  # minimum length: 16 (IV) + 16 (one AES block)
+     raise ValueError("Invalid encrypted data length")
 iv = decoded_data[:16]
 if isinstance(secret_key, str):
     secret_key = secret_key.encode("utf-8")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
iv = decoded_data[:16]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
cipher = AES.new(secret_key.ljust(32)[:32], AES.MODE_CBC, iv)
decrypted_data = cipher.decrypt(encrypted_data[16:])
decrypted_data = cipher.decrypt(decoded_data[16:])
decoded_data = urlsafe_b64decode(secret_str)
if len(decoded_data) < 32: # minimum length: 16 (IV) + 16 (one AES block)
raise ValueError("Invalid encrypted data length")
iv = decoded_data[:16]
if isinstance(secret_key, str):
secret_key = secret_key.encode("utf-8")
cipher = AES.new(secret_key.ljust(32)[:32], AES.MODE_CBC, iv)
decrypted_data = cipher.decrypt(decoded_data[16:])

@mhdzumair
Copy link
Owner

This is a good finding, I remember that I changed this method with my test cases for good compression and speed. So even with this, we're always going to hit the URL max size (according to pydantic validation its 2083 chars).

I think it's better to go for storing the encrypted text in REDIS with 1 month of expire & when getting the data from Redis, we can use REDIS_ASYNC_CLIENT.getex method to update the expiry on active user. This will automatically clean up the user config who're not using the MF or stale config.

The Encrypt logic

user data -> encrypt with server secret -> find the md5 hash (32 chars) + random chars with dynamic length (5-18 chars to harden the prediction) so always this will be a lesser than 50 chars -> store in Redis as key as user_{hash+random chars} & value as user config. -> return the hash+random chars as secret_str

The Decrypt logic

This will be in the reverse. We know the secret_str then find it from Redis or raise an error (don't use default config, this might be issue where a user configured RD for safety then if he doesn't use MF for 1 month and try to use it then it accidentally open up the torrent).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants